//
//  LXJComposeButton.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/4/4.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit

/// 自定义撰写摁扭 图在上 文字在下

class LXJComposeButton: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        /// 界面加载
        setupUI()
    }
    
    /// 不使用 XIB 加载
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 便利构造函数
    convenience init(title: String, imageName: String?, target: Any, action: Selector) {
        self.init()
        /// 设置标题
        setTitle(title, for: .normal)
        /// 标题颜色
        setTitleColor(UIColor.darkGray, for: .normal)
        /// 标题字号
        self.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        /// 设置图片
        setImage(UIImage(named: imageName ?? ""), for: .normal)
        /// 监听标题的点击事件
        addTarget(target, action: action, for: .touchUpInside)
    }
    
    // MARK: 页面搭建
    fileprivate func setupUI() -> Void {
        /// 图片居中显示
        imageView?.contentMode = .center
        /// 文字居中显示
        titleLabel?.textAlignment = .center
    }
    
    /// 调整子空间的布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        /// 设置图片的y轴
        imageView?.frame.origin.y = 0
        imageView?.frame.origin.x = 0
        
        /// 设置图片的大小
        imageView?.frame.size.width = bounds.size.width
        imageView?.frame.size.height = bounds.size.width
        
        /// 设置titlelabe的y轴, 当前按钮的高度减去按钮的高度表示titleLabel的y轴
        titleLabel?.frame.origin.y = bounds.size.width
        titleLabel?.frame.origin.x = 0
        
        /// 设置文字的大小
        titleLabel?.frame.size.width = bounds.size.width
        titleLabel?.frame.size.height = bounds.size.height - bounds.size.width
    }
}
